package com.example.index.controller;


import com.example.index.mapper.CollectMapper;
import com.example.index.service.impl.CollectServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.yc.biz.BizException;
import com.yc.pojo.Collect;
import com.yc.pojo.CollectDTO;
import com.yc.pojo.House;
import com.yc.vo.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lxh
 * @since 2023-07-05
 */
@RestController
@RequestMapping("collect")
public class CollectController {

    @Resource
    CollectServiceImpl collectService;

    @Resource
    CollectMapper collectMapper;

    @Resource
    HouseController houseController;

    @RequestMapping("insertCollect")
    Result insertCollect(Integer houseId, Integer userId){
        try {
            collectService.insertCollect(userId, houseId);
            return Result.success("收藏成功!");
        } catch (BizException e) {
            e.printStackTrace();
            return Result.failure(e.getMessage());
        }
    }

    @RequestMapping("deleteCollect")
    Result deleteCollect(Integer houseId, Integer userId){
        try {
            collectService.deleteCollect(userId, houseId);
            return Result.success("取消成功!");
        } catch (BizException e) {
            e.printStackTrace();
            return Result.failure(e.getMessage());
        }
    }

    @RequestMapping("selectCollects")
    List selectCollects(Integer userId){
        MPJLambdaWrapper mpjLambdaWrapper = new MPJLambdaWrapper<CollectDTO>()
                .selectAll(House.class)
                .selectAll(Collect.class)
                .innerJoin(House.class, House::getId, Collect::getHouseId)
                .eq(Collect::getUserId, userId)
                .orderByDesc(Collect::getId);
        final List<CollectDTO> collects = collectMapper.selectJoinList(CollectDTO.class, mpjLambdaWrapper);
        if (collects.isEmpty() == false){
            for (CollectDTO collect : collects) {
                final Integer houseId = collect.getHouseId();
                final String image = houseController.image(houseId);
                collect.setImage(image);
            }
        }
        return collects;
    }


}
